<template>
  <div>
    <!--<Row>-->
      <!--<Col span="7">-->
        <!--<div class="input-card" style="width: 19rem;height: 100%;">-->
          <!--<div style="height: 70%">-->
            <!--<h2>车位状态</h2>-->
            <!--<Row style="margin-left: 30px;margin-top: 10px">-->
              <!--<Col span="12" style="color:#f56c6c">红色:占有</Col>-->
              <!--<Col span="12" style="color: #67c23a">绿色:空闲</Col>-->
            <!--</Row>-->
            <!--<Row style="margin-left: 30px">-->
              <!--<Col span="12" style="color:#409eff">蓝色:初始化</Col>-->
              <!--<Col span="12" style="color:#bbbcbd">灰色:离线</Col>-->
            <!--</Row>-->
            <!--<Row style="margin-top: 10px;height: 70%;border-radius: 0.4rem;box-shadow: 0px 0px 6px 0px rgba(114, 124, 245, 0.5);">-->
              <!--&lt;!&ndash;<Table height="300" :columns="columns" :data="parkingSpaceList"></Table>&ndash;&gt;-->
                <!--<div v-for="parkSpace in parkingSpaceList" class="tagGroup">-->
                  <!--&lt;!&ndash; status  用来判断边框的颜色 &ndash;&gt;-->
                  <!--<div class="tagBtnn tag-success" v-if="parkSpace.status==0">{{parkSpace.code }}</div>-->
                  <!--<div class="tagBtnn tag-danger" v-if="parkSpace.status==1">{{parkSpace.code }}</div>-->
                  <!--<div class="tagBtnn tag-info" v-if="parkSpace.status==4">{{parkSpace.code }}</div>-->
                  <!--<div class="tagBtnn" v-if="parkSpace.status==2">{{parkSpace.code }}</div>-->
                <!--</div>-->
            <!--</Row>-->
          <!--</div>-->
          <!--<div>-->
            <!--<Row>-->
              <!--<h2>车位统计:</h2>-->
            <!--</Row>-->
            <!--<Row class="input-item">-->
              <!--<Col span="12">占用数:</Col>-->
              <!--<Col span="12">总数:</Col>-->
            <!--</Row>-->
          <!--</div>-->
          <!--&lt;!&ndash;底部连接状态&ndash;&gt;-->
          <!--<div class="footStatusClz">-->
            <!--<div class="footStatusTxtClz">连接状态:</div>-->
            <!--<div style="float: left;margin-right: 1px;margin-top: 4px;">-->
              <!--<div v-if="websocketStatus!=3" style="float: left;margin-left: 3px;" class="connectClz"></div>-->
              <!--<span v-if="websocketStatus!=3" class="footStatusTxtClz" style="margin-left: 2px;margin-top: -3px;">连接</span>-->
              <!--<div v-if="websocketStatus==3" style="float: left;margin-left: 3px;" class="disconnectClz"></div>-->
              <!--<span v-if="websocketStatus==3" class="footStatusTxtClz" style="margin-left: 2px;margin-top: -3px;">断开</span>-->
            <!--</div>-->
          <!--</div>-->
        <!--</div>-->
      <!--</Col>-->
      <!--<Col span="17">-->
        <!--<div id="mapShow" style="width: 100%;height: 500px;margin-left: 306px;"></div>-->
      <!--</Col>-->

    <!--</Row>-->
    <div style="width: 100%;height: 100%">
      <div class="lftCont">
        <div class="input-card" style="height: 100%;">
          <div style="height: 67%">
            <h2>车位状态</h2>
            <Row style="margin-left: 30px;margin-top: 10px">
              <Col span="12" style="color:#f56c6c">红色:占有</Col>
              <Col span="12" style="color: #67c23a">绿色:空闲</Col>
            </Row>
            <Row style="margin-left: 30px">
              <Col span="12" style="color:#409eff">蓝色:初始化</Col>
              <Col span="12" style="color:#bbbcbd">灰色:离线</Col>
            </Row>
            <Row class="stateBlock" style="margin-top: 10px;height: 73%;overflow-y: scroll;border-radius: 0.4rem;box-shadow: 0px 0px 6px 0px rgba(114, 124, 245, 0.5);">
              <!--<Table height="300" :columns="columns" :data="parkingSpaceList"></Table>-->
              <div v-for="parkSpace in parkingSpaceList" class="tagGroup">
                <!-- status  用来判断边框的颜色 -->
                <div class="tagBtnn tag-success" v-if="parkSpace.status==0">{{parkSpace.code }}</div>
                <div class="tagBtnn tag-danger" v-if="parkSpace.status==1">{{parkSpace.code }}</div>
                <div class="tagBtnn tag-info" v-if="parkSpace.status==4">{{parkSpace.code }}</div>
                <div class="tagBtnn" v-if="parkSpace.status==2">{{parkSpace.code }}</div>
              </div>
            </Row>
          </div>
          <div>
            <Row style="margin-bottom: 10px">
              <h2>车位统计:</h2>
            </Row>
            <Row class="input-item">
              <Col span="12">占用数:{{parkingSpaceUseNumShow.useNum}}</Col>
              <Col span="12">总数:{{parkingSpaceUseNumShow.totalNum}}</Col>
            </Row>
          </div>
          <!--底部连接状态-->
          <div class="footStatusClz">
            <div class="footStatusTxtClz">连接状态:</div>
            <div style="float: left;margin-right: 1px;margin-top: 4px;">
              <div v-if="websocketStatus!=3" style="float: left;margin-left: 3px;" class="connectClz"></div>
              <span v-if="websocketStatus!=3" class="footStatusTxtClz" style="margin-left: 2px;margin-top: -3px;">连接</span>
              <div v-if="websocketStatus==3" style="float: left;margin-left: 3px;" class="disconnectClz"></div>
              <span v-if="websocketStatus==3" class="footStatusTxtClz" style="margin-left: 2px;margin-top: -3px;">断开</span>
            </div>
          </div>
        </div>
      </div>
      <div class="rgtMap">
        <div id="mapShow"></div>
      </div>
    </div>

    <div class="select-card" style="width: 14rem;height: 3rem;margin-left: 310px;">
      <Select id="selLot" clearable v-model="selPark" size="large" style="width: 230px;margin-left: -21px;margin-top: -13px;" placeholder="请选择停车场" @on-change="changeParkingInfo(selPark)">
        <Option v-for="item in markerList" :value="item.id" :key="item.lotName">{{ item.lotName }}</Option>
      </Select>
    </div>
  </div>
</template>

<script>
  // 创建构造器
  // var closeInfoWindowComponent = Vue.extend({
  //   template: "<div class='content-window-card'><div class='info-top'>" +
  //   "<p class='input-item'>名称：'+obj.lotName+'</p><p class='img' v-on:click='closeInfoWindow'>X</p></div>" +
  //   "<div class='info-middle'><p class='input-item'>地址：'+obj.address+'</p></div></div>",
  //   data: function () {
  //     return {
  //       lotName: '',
  //       address: ''
  //     }
  //   },
  //   methods:{
  //     // 关闭信息窗体
  //     closeInfoWindow() {
  //       console.log(777)
  //       // map.clearInfoWindow();
  //       infoWindow.close(function(){
  //         console.log(666)
  //       })
  //     },
  //   }
  // })
  // // 创建 Profile 实例，并挂载到一个元素上。
  // let fmc = new closeInfoWindowComponent().$mount();
  // new Profile().$mount('#mount-point');

  import urlSource from '../../api/urlSource'

  let mapShow;
  let markerShow=[];
  let infoWindow = '';
  // let markerList = [];
  let geocoder;
  let addr;
  export default {
    name: "showDeviceMap",
    components: {},
    data() {
      return {
        tmpMarker:'',
        // columns: [
        //     {
        //     title: '车位编号',
        //     key: 'code'
        //   },
        //   {
        //     title: '状态',
        //     key: 'status',
        //     render: (h, params) => {
        //       var statusName = "";
        //       this.spaceStatus.forEach(v => {
        //         if(params.row.status==null || params.row.status==''){//设备重启，状态显示为初始化
        //           params.row.status = 2;
        //         }
        //         if (v.key == params.row.status) {
        //           statusName = v.value;
        //         }
        //       })
        //       return h('div', [
        //         h('div',{
        //           class: (params.row.status==0)? "tagBtnn tag-success" : (params.row.status==1)? "tagBtnn tag-danger" : "tagBtnn"
        //
        //         }, statusName)
        //       ]);
        //     }
        //   },
        // ],
        spaceStatus: [
          {
            key: 0,
            value: "空闲",
          },
          {
            key: 1,
            value: "占有",
          },
          {
            key: 2,
            value: "初始化",
          },
          {
            key: 4,
            value: "离线",
          }
        ],
        lotName:'',
        parkingList:'',
        address:'',
        parkingSpaceList:[],
        code:'',
        orgId:'',
        id:'',
        selPark: '',
        markerList: [],
        ipAddr: '',
        websocketStatus: '',
        tabHeightTemp: 0,
        parkingSpaceUseNumShow:{
          'useNum':'',
          'totalNum':''
        }
      }
    },
    methods: {
      initMap() {
        mapShow = new AMap.Map('mapShow', {
          resizeEnable: true,
          zoom: 9,
          center: [108.947509,34.260749]
        });
      },

      //构建自定义信息窗体
      createInfoWindow(mark,obj) {
        //构建信息窗体中显示的内容
        let info = [];
        info.push("<div class='content-window-card'> ");
        info.push("<div style='padding:10px;'>");
        info.push("<p class='input-item'>名称："+obj.lotName+"</p>");
        info.push("<p class='input-item'>地址："+obj.address+"</p></div></div>");

        infoWindow = new AMap.InfoWindow({
          // isCustom: true,  //使用自定义窗体
          content: info.join("")  //使用默认信息窗体框样式，显示信息内容
        });

        infoWindow.open(mapShow, mark.getPosition());

      },
      //关闭信息窗体
      // closeInfoWindow() {
      //   console.log(777)
      //   // map.clearInfoWindow();
      //   infoWindow.close(function(){
      //     console.log(666)
      //   })
      // },

      //逆地址编码
      regeoCode(lnglat,obj,callbackFn) {
        if(!geocoder){
          geocoder = new AMap.Geocoder({
            city: "010", //城市设为北京，默认：“全国”
            radius: 1000 //范围，默认：500
          });
        }

        geocoder.getAddress(lnglat, function(status, result) {
          if (status === 'complete'&&result.regeocode) {
            addr = result.regeocode.formattedAddress;
            obj.address = addr;
            if(callbackFn && typeof callbackFn == "function"){
              callbackFn();
            }
          }else{
            alert(JSON.stringify(result))
          }
        });
      },
      showCurrentOrgAllMapMarker(){
        let _this = this;
        this.markerList.forEach(function(marker) {
          let mark = new AMap.Marker({
            icon: new AMap.Icon({
              size: new AMap.Size(40, 40),//图标大小
              imageSize: new AMap.Size(40, 40),
              image: urlSource.imageUrl + "icon/parking.png"
            }),
            position: [marker.position[0], marker.position[1]],
          });
          mark.setMap(mapShow);

          AMap.event.addListener(mark, 'click', function () {
            console.log(321)
            _this.clearMarker();
            let testFn = function(){
              let mark = new AMap.Marker({
                icon: new AMap.Icon({
                  size: new AMap.Size(40, 40),//图标大小
                  imageSize: new AMap.Size(40, 40),
                  image: urlSource.imageUrl + "icon/gps.png"
                }),
                position: [marker.position[0], marker.position[1]],
              });
              mark.setMap(mapShow);

              mapShow.panTo([marker.position[0], marker.position[1]]);
              _this.lotName = marker.lotName;
              _this.code = marker.code;
              _this.parkingSpaceList = marker.spaceList;
              _this.parkingSpaceUseNumShow.totalNum = marker.totalNum;
              _this.parkingSpaceUseNumShow.useNum = marker.usingNum;
              _this.tmpMarker = mark;
              _this.createInfoWindow(mark,_this);
            }
            _this.regeoCode(marker.position,_this,testFn);
          });
        })
      },

    //获取当前机构下所有的停车场
      getAllLotsByOrg(orgId){
        let url = urlSource.apiUrl + "parkingLots/" + this.$store.state.user.orgId + "/parkingLotsAndSpaces"
        this.$http.get(url).then(res => {
          this.parkingList = res.data;
          console.log(this.parkingList)
          this.parkingList.forEach(v => {
            let tmp = {};
            tmp.lotName = v.name;
            // tmp.icon = '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-3.png';
            tmp.position = [v.longitude,v.latitude];
            tmp.orgId = v.orgId;
            tmp.code = v.code;
            tmp.address = v.address;
            tmp.id = v.id;
            tmp.totalNum = v.totalNum;
            v.parkingSpaceList.forEach(d => {
              if(d.updateTime){
                if(!d.deviceId){
                  d.status = '2';
                }else{
                  let betweenTime =  new Date().getTime() - this.dateStr2dateMills(d.updateTime);
                  if(d.heartBeat){//heartBeat 为1，代表十秒
                    if(betweenTime > d.heartBeat*10*1000){
                      d.status = '4';
                    }
                  }else{
                    //如果 heartBeat 没有值，默认5min 分钟就处于休眠状态
                    if(betweenTime > 5*60*1000){
                      d.status = '4';
                    }
                  }
                }
              }
            });
            let useNum = 0;
            v.parkingSpaceList.forEach(r => {
              if(r.status=='1'){
                useNum++;
              }
            });
            tmp.usingNum = useNum;
            tmp.spaceList = v.parkingSpaceList;
            this.markerList.push(tmp);
          });
          this.showCurrentOrgAllMapMarker();
        }).catch(err => {

        })
      },
      //时间字符串转毫秒值
      dateStr2dateMills(time){
        time = time.replace(new RegExp("-","gm"),"/");
        return (new Date(time)).getTime();
      },
      changeParkingInfo(val){
        this.clearMarker();
        if(val){
          let marker = '';
          this.markerList.forEach(v => {
            if(val == v.id){
              marker = v;
              return;
            }
          });
          mapShow.panTo([marker.position[0], marker.position[1]]);
          this.regeoCode(marker.position,this);
          this.lotName = marker.lotName;
          this.code = marker.code;
          this.parkingSpaceList = marker.spaceList;
          this.parkingSpaceUseNumShow.totalNum = marker.totalNum;
          this.parkingSpaceUseNumShow.useNum = marker.usingNum;
          let mark = new AMap.Marker({
            /*icon: new AMap.Icon({
              size: new AMap.Size(40, 40),//图标大小
              imageSize: new AMap.Size(60, 60),
              // image: urlSource.imageUrl + "icon/gps.png"
            }),*/
            icon: urlSource.imageUrl + "icon/gps.png",
            position: [marker.position[0], marker.position[1]],
          });
          mark.setMap(mapShow);
          this.tmpMarker = mark;
        }
      },
      clearMarker(){
        mapShow.remove(this.tmpMarker);
      },
      initWebSocket() {
        if ('WebSocket' in window) {
          this.websocket = new WebSocket(urlSource.socketUrl)
        } else {
          alert('当前浏览器 Not support websocket')
        }
        //连接错误
        this.websocket.onerror = this.setErrorMessage
        //连接成功
        this.websocket.onopen = this.setOnopenMessage
        //收到消息的回调
        this.websocket.onmessage = this.setOnmessageMessage
        //连接关闭的回调
        this.websocket.onclose = this.setOncloseMessage
        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = this.onbeforeunload
      },
      setErrorMessage() {
        this.data = "WebSocket连接发生错误" + '   状态码：' + this.websocket.readyState;
      },
      setOnopenMessage() {
        this.websocketStatus = this.websocket.readyState;
        this.data = "WebSocket连接成功" + '   状态码：' + this.websocket.readyState;
      },
      setOnmessageMessage(event) {
        this.data = event.data;
        this.getServerDeviceData(this.data);
      },
      //即时推送设备数据
      getServerDeviceData(pData){
        if(pData && this.parkingSpaceList){
          let dataObj = JSON.parse(pData);
          console.log(dataObj)
          this.parkingSpaceList.forEach(v => {
            if(dataObj.deivceCode == v.code){
              v.status = dataObj.data.ParkingState;
            }else{
              let betweenTime =  new Date().getTime() - this.dateStr2dateMills(v.updateTime);
              if(v.HeartBeat){//heartBeat 为1，代表十秒
                if(betweenTime > v.HeartBeat*10*1000){
                  v.status = '4';
                }
              }else{
                //如果 heartBeat 没有值，默认5min 分钟就处于休眠状态
                if(betweenTime > 5*60*1000){
                  v.status = '4';
                }
              }
            }
          });
          // 即时统计车位占用情况
          let useNum = 0;
          this.parkingSpaceList.forEach(r => {
            if(r.status=='1'){
              useNum++;
            }
          });
          this.parkingSpaceUseNumShow.useNum = useNum;
        }
      },
      setOncloseMessage() {
        this.websocketStatus = this.websocket.readyState;
        this.data = "WebSocket连接关闭" + '   状态码：' + this.websocket.readyState;
      },
      onbeforeunload() {
        this.closeWebSocket();
      },
      //websocket发送消息
      send() {
        this.websocket.send(this.text)
        this.text = ''
      },
      closeWebSocket() {
        this.websocket.close()
      },
    },
    mounted() {
      this.$nextTick(() => {
        this.initMap();
        this.getAllLotsByOrg(this.$store.state.user.orgId);
        this.initWebSocket();
        this.ipAddr = localStorage.getItem('Ip');
      }),
      this.tabHeightTemp = window.innerHeight-186;
    },
    beforeDestroy() {
      this.onbeforeunload();
    }
  }
</script>

<style >
  .stateBlock::-webkit-scrollbar {/* 滚动条整体部分 */
    width: 8px;
    height: 10px
  }
  .stateBlock::-webkit-scrollbar-button:vertical {
    display: none
  }
  .stateBlock::-webkit-scrollbar-corner,
  .stateBlock::-webkit-scrollbar-track {
    background-color: #fff
  }
  .stateBlock::-webkit-scrollbar-thumb {
    border-radius: 5px;
    background-color: rgba(0, 0, 0, .3)
  }
  .stateBlock::-webkit-scrollbar-thumb:vertical:hover {
    background-color: rgba(0, 0, 0, .35)
  }
  .stateBlock::-webkit-scrollbar-thumb:vertical:active {
    background-color: rgba(0, 0, 0, .38)
  }
  .input-card{
    position: fixed;
    display: flex;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-color: #fff;
    background-clip: border-box;
    border-radius: .25rem;
    width: 23.1%;
    /*width: 22rem;*/
    border-width: 0;
    border-radius: 0.4rem;
    box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
    top: 108px;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    padding: 0.75rem 1.25rem;
  }
  .select-card{
    position: fixed;
    display: flex;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-clip: border-box;
    border-radius: .25rem;
    width: 22rem;
    border-width: 0;
    border-radius: 0.4rem;
    /*box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);*/;
    /*bottom: 1rem*/
    top: 108px;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    padding: 0.75rem 1.25rem;
  }
  .custom-info {
    border: solid 1px silver;
  }

  div.info-top {
    position: relative;
    background: none repeat scroll 0 0 #F9F9F9;
    border-bottom: 1px solid #CCC;
    border-radius: 5px 5px 0 0;
  }

  div.info-top div {
    display: inline-block;
    color: #333333;
    font-size: 14px;
    font-weight: bold;
    line-height: 31px;
    padding: 0 10px;
  }

  div.info-top img {
    position: absolute;
    top: 10px;
    right: 10px;
    transition-duration: 0.25s;
  }

  div.info-top img:hover {
    box-shadow: 0px 0px 5px #000;
  }

  div.info-middle {
    font-size: 12px;
    padding: 10px 6px;
    line-height: 20px;
  }

  div.info-bottom {
    height: 0px;
    width: 100%;
    clear: both;
    text-align: center;
  }

  div.info-bottom img {
    position: relative;
    z-index: 104;
  }

 /* span {
    margin-left: 5px;
    font-size: 11px;
  }*/

  .info-middle img {
    float: left;
    margin-right: 6px;
  }
  .tagGroup{
    float: left;
  }
  .tagBtnn {
    background-color: rgba(64, 158, 255, 0.15);
    text-align: center;
    font-size: 14px;
    color: #409eff;
    border-radius: 4px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border: 1px solid rgba(64, 158, 255, 0.2);
    white-space: nowrap;
    font-weight: bold;
    padding: 8px 0;
    margin: 5px;
    width: 119px;
   }
  .tag-success{
    background-color: rgba(103,194,58,.15);
    border-color: rgba(103,194,58,.2);
    color: #67c23a;
  }
  .tag-danger {
    background-color: hsla(0,87%,69%,.15);
    border-color: hsla(0,87%,69%,.2);
    color: #f56c6c;
  }
  .tag-info {
    background-color: gainsboro;
    border-color: ghostwhite;
    color: grey;
  }
  .footStatusClz {
    position: fixed;
    bottom: 0px;
    left: 211px;
    background: #ddd;
    width:100%;
    height: 21px;
    padding-left: 20px;
    z-index: 999;
  }
  .connectClz {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    border: 1px solid #22de22;
    background: #22de22;
  }
  .disconnectClz {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    border: 1px solid red;
    background: red;
  }
  .footStatusTxtClz {
    color: #333;
    float: left;
    margin-right: 6px;
  }
  .content-window-card{
    position: relative;
    width: 18rem;
    box-shadow: none;
    /*bottom: 28px;*/
    /*left: 10px;*/
    background-color: #fff;
    /*border: solid 1px silver;*/
    bottom: 0;
    left: 0;
  }
  .input-item{
    font-size: 14px;
  }
  /*.content-window-card .info-top {*/
    /*position: relative;*/
    /*background: none repeat scroll 0 0 #F9F9F9;*/
    /*border-bottom: 1px solid #CCC;*/
    /*border-radius: 5px 5px 0 0;*/
  /*}*/
  /*.content-window-card .info-top p.input-item {*/
    /*display: inline-block;*/
    /*color: #333333;*/
    /*font-size: 14px;*/
    /*font-weight: bold;*/
    /*line-height: 31px;*/
    /*padding: 0 10px;*/
  /*}*/
  /*.content-window-card .info-top .img {*/
    /*position: absolute;*/
    /*top: 5px;*/
    /*right: 7px;*/
    /*transition-duration: 0.25s;*/
  /*}*/
  /*.content-window-card .info-middle {*/
    /*font-size: 12px;*/
    /*padding: 10px;*/
    /*line-height: 20px;*/
  /*}*/
  html,body{
    height: 100%;
    overflow:hidden;
  }
  .ivu-layout{
    width: 100%;
    height: 100%;
  }
  .lftCont{
    float: left;
    width:23.1%;
    height: 100%
  }
  .rgtMap{
    /*width: 78%;*/
    /*height: 100%;*/
    /*overflow: hidden;*/
    height: 100%;
    width: 78%;
    margin-left: 27%
  }
  #mapShow{
    /*width: 78%;*/
    height: 100%;
    position: absolute!important;
    width: 63%;
  }
</style>
